package com.example.simpletask

import android.app.Dialog
import android.content.Context
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView

class MissionAdapter(val context: Context, val missionList: ArrayList<Mission>, val dbHelper: DbHelper)
    : RecyclerView.Adapter<MissionAdapter.ViewHolder>() {

    /**
     * 这个可以理解为RecyclerView渲染的样式，只是在View之上套了一层holder
     */
    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val title = view.findViewById<TextView>(R.id.missionTitle)
        val progressBar = itemView.findViewById<CardView>(R.id.progressbar)

//        这个函数可以根据步骤数和进度数自动改变颜色和进度条长度
        fun setStage(steps: Int, stage: Int) {
            val background = itemView as CardView
            background.setCardBackgroundColor(BgColor.get(steps, stage))
            val params = progressBar.layoutParams
            val width = 210f * stage / steps
            val scale: Float = itemView.resources.displayMetrics.density
            params.width = (width * scale).toInt()
            progressBar.layoutParams = params
        }
    }

    companion object {
//        这个静态变量主要记录手指刚接触到任务卡片时的位置，因为只处理x轴的所以只有x
        private var startX: Float = 0f

        /**
         * 是否成功
         * 由于手指在卡片上移动都会被ontouchlistener记录到，所以很容易使卡片变了色继续变色
         * 所以通过这个布尔值可以让完成变色后剩余的操作不影响结果
         */
        private var succeed: Boolean = false
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
//        将view指定为mission_card.xml
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.mission_card, parent, false)
//        将view装载入viewHolder
        val viewHolder = ViewHolder(view)

//        任务卡片长按弹出删除选项
        viewHolder.itemView.setOnLongClickListener {
            val dialog = Dialog(context, android.R.style.ThemeOverlay_Material_Dialog_Alert)
            val deleteView = LayoutInflater.from(context)
                .inflate(R.layout.dialog_delete, parent, false)
            dialog.setContentView(deleteView)
            dialog.show()

            val deleteBtn = deleteView.findViewById<TextView>(R.id.deleteBtn)
            deleteBtn.setOnClickListener {
                val position = viewHolder.adapterPosition
//                在数据库中删除
                dbHelper.deleteMission(missionList[position].getId())
//                在页面中删除
                missionList.removeAt(position)
                notifyDataSetChanged()
//                关闭dialog
                dialog.dismiss()
            }
            true
        }

//        任务卡片左滑右滑改变进度
        viewHolder.itemView.setOnTouchListener { view, motionEvent ->
            val position = viewHolder.adapterPosition
            val mission = missionList[position]
            when(motionEvent.action) {
//                在手指刚接触到卡片时记录开始的x，并将是否操作成功置为false
                MotionEvent.ACTION_DOWN -> {
                    startX = motionEvent.rawX
                    succeed = false
                }
                MotionEvent.ACTION_MOVE -> {
                    val x = motionEvent.rawX

                    if (x - startX > 50f && !succeed) {
                        mission.decreaseStage()
                        viewHolder.setStage(mission.getSteps(), mission.getStage())
                        dbHelper.updateStage(mission.getId(), mission.getStage())
                        succeed = true
                    } else if (x - startX < -50f && !succeed) {
                        mission.increaseStage()
                        viewHolder.setStage(mission.getSteps(), mission.getStage())
                        dbHelper.updateStage(mission.getId(), mission.getStage())
                        succeed = true
                    }
                }
            }
            false
        }

//        点击任务卡片进入编辑菜单
        viewHolder.itemView.setOnClickListener {
            val position = viewHolder.adapterPosition
            val mission = missionList[position]
            EditActivity.start(context, mission.getId(), mission.getContent()
                , mission.getSteps(), mission.getStage(), 0)
        }

        return viewHolder
    }

    override fun getItemCount(): Int = missionList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val mission = missionList[position]
        var content = mission.getContent()
        if (content.length > 10)
            content = content.substring(0, 10) + "..."
        holder.title.text = content

        holder.setStage(mission.getSteps(), mission.getStage())
    }
}